package org.jeecg.modules.data.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.data.entity.District;
import org.jeecg.modules.data.entity.TDataReport;
import org.jeecg.modules.data.entity.TDataStatistics;
import org.jeecg.modules.data.entity.TInvestigationRelease;
import org.jeecg.modules.data.service.IDistrictService;
import org.jeecg.modules.data.service.ITDataReportService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.data.service.ITDataStatisticsService;
import org.jeecg.modules.data.service.ITInvestigationReleaseService;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.model.DistrictIdModel;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserDistrictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: t_data_report
 * @Author: jeecg-boot
 * @Date:   2025-05-20
 * @Version: V1.0
 */
@Api(tags="t_data_report")
@RestController
@RequestMapping("/data/tDataReport")
@Slf4j
public class TDataReportController extends JeecgController<TDataReport, ITDataReportService> {
	 @Resource
	 private ITDataReportService tDataReportService;
	 @Resource
	 private ISysUserDistrictService sysDistrictService;
	 @Resource
	 private ISysDictService sysDictService;
	 @Resource
	 private ITInvestigationReleaseService tInvestigationReleaseService;
	 @Resource
	 private IDistrictService districtService;

	/**
	 * 分页列表查询
	 *
	 * @param tDataReport
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="t_data_report-分页列表查询", notes="t_data_report-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TDataReport>> queryPageList(TDataReport tDataReport,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		QueryWrapper<TDataReport> queryWrapper = QueryGenerator.initQueryWrapper(tDataReport, req.getParameterMap());
		// 县级上报数据，只能查看自己上报的数据。
/*		queryWrapper.eq("create_by", user.getUsername());
		queryWrapper.orderByDesc("create_time");*/
		tDataReport.setCreateBy(user.getUsername());
		Page<TDataReport> page = new Page<TDataReport>(pageNo, pageSize);
		IPage<TDataReport> pageList = tDataReportService.selectPageList(page, tDataReport);
		/*pageList.getRecords().stream().forEach(item->{
			TInvestigationRelease ti = tInvestigationReleaseService.getById(item.getInvestigationId());
			String text = sysDictService.queryDictTextByKey("crop_type", ti.getCropType());
			item.setInvestigationName(text);
		});*/
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tDataReport
	 * @return
	 */
	@AutoLog(value = "t_data_report-添加")
	@ApiOperation(value="t_data_report-添加", notes="t_data_report-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TDataReport tDataReport) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		// 根据登录用户获取所属区县
		District district = sysDistrictService.queryDistrictByUserId(user.getId());
		if (district == null) {
			return Result.OK("当前登录用户未绑定所属区县，请联系管理员！");
		}
		tDataReport.setCreateBy(user.getUsername());
		tDataReport.setCreateTime(new Date());
		String area = district.getCantCode(); // 区县编码
		String city = districtService.getParentDistrict(area).getCantCode(); // 城市
		String cityName = districtService.getParentDistrict(area).getShortName(); // 城市名称
		String province = districtService.getParentDistrict(city).getCantCode(); // 省份
		String provinceName = districtService.getParentDistrict(city).getShortName(); // 省份名称
		tDataReport.setCantCode(province+":"+city+":"+area);
		TDataStatistics statistics = new TDataStatistics();
		statistics.setInvestigationId(tDataReport.getInvestigationId());
		statistics.setCantCode(area);
		statistics.setCantName(district.getShortName());
		statistics.setCity(city);
		statistics.setCityName(cityName);
		statistics.setProvince(province);
		statistics.setProvinceName(provinceName);
		statistics.setCreateBy(user.getUsername());
		statistics.setCreateTime(new Date());
		statistics.setAverageLossRate(tDataReport.getLossRate());
		tDataReportService.saveReportAndStatis(tDataReport, statistics);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tDataReport
	 * @return
	 */
	@AutoLog(value = "t_data_report-编辑")
	@ApiOperation(value="t_data_report-编辑", notes="t_data_report-编辑")
	@PostMapping(value = "/edit")
	public Result<String> edit(@RequestBody TDataReport tDataReport) {
		TInvestigationRelease ti = tInvestigationReleaseService.getById(tDataReport.getInvestigationId());
		if (ti != null) {
			if (ti.getStatus().equals("2")) {
				return Result.error("该调查发布已过期，无法编辑！");
			}
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		// 根据登录用户获取所属区县
		District district = sysDistrictService.queryDistrictByUserId(user.getId());
		if (district == null) {
			return Result.OK("当前登录用户未绑定所属区县，请联系管理员！");
		}
		tDataReport.setUpdateBy(user.getUsername());
		tDataReport.setUpdateTime(new Date());
		String area = district.getCantCode(); // 区县编码
		String city = districtService.getParentDistrict(area).getCantCode(); // 城市
		String cityName = districtService.getParentDistrict(area).getShortName(); // 城市名称
		String province = districtService.getParentDistrict(city).getCantCode(); // 省份
		String provinceName = districtService.getParentDistrict(city).getShortName(); // 省份名称
		tDataReport.setCantCode(province+":"+city+":"+area);
		TDataStatistics statistics = new TDataStatistics();
		statistics.setCantCode(area);
		statistics.setCantName(district.getShortName());
		statistics.setCity(city);
		statistics.setCityName(cityName);
		statistics.setProvince(province);
		statistics.setProvinceName(provinceName);
		statistics.setUpdateBy(user.getUsername());
		statistics.setUpdateTime(new Date());
		statistics.setAverageLossRate(tDataReport.getLossRate());
		statistics.setInvestigationId(tDataReport.getInvestigationId());
		tDataReportService.updateReportAndStatis(tDataReport, statistics);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param tDataReport
	 * @return
	 */
	@AutoLog(value = "t_data_report-通过id删除")
	@ApiOperation(value="t_data_report-通过id删除", notes="t_data_report-通过id删除")
	@PostMapping(value = "/delete")
	public Result<String> delete(@RequestBody TDataReport tDataReport) {
		TDataReport tr = tDataReportService.getById(tDataReport.getId());
		TInvestigationRelease ti = tInvestigationReleaseService.getById(tr.getInvestigationId());
		if (ti != null) {
			if (ti.getStatus().equals("2")) {
				return Result.error("该调查发布已过期，无法删除！");
			}
		}
		tDataReportService.deleteAndStatis(tDataReport.getId());
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param tDataReport
	 * @return
	 */
	@AutoLog(value = "t_data_report-批量删除")
	@ApiOperation(value="t_data_report-批量删除", notes="t_data_report-批量删除")
	@PostMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestBody TDataReport tDataReport) {
		String ids = tDataReport.getId();
		for (String id : ids.split(",")) {
			TInvestigationRelease ti = tInvestigationReleaseService.getById(id);
			if (ti != null) {
				if (ti.getStatus().equals("2")) {
					return Result.OK("该调查发布已过期，无法删除！");
				} else {
					tDataReportService.deleteAndStatis(tDataReport.getId());
				}
			}
		}
//		this.tDataReportService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "t_data_report-通过id查询")
	@ApiOperation(value="t_data_report-通过id查询", notes="t_data_report-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TDataReport> queryById(@RequestParam(name="id",required=true) String id) {
		TDataReport tDataReport = tDataReportService.getById(id);
		if(tDataReport==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tDataReport);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tDataReport
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TDataReport tDataReport) {
        return super.exportXls(request, tDataReport, TDataReport.class, "t_data_report");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TDataReport.class);
    }

	 /**
	  * 统计县查看明细列表
	  *
	  * @param tDataReport
	  * @return
	  */
	 @ApiOperation(value="t_data_statistics-统计县查看明细列表", notes="t_data_statistics-统计县查看明细列表")
	 @GetMapping(value = "/areaList")
	 public Result<List<TDataReport>> queryAreaList(TDataReport tDataReport) {
		 List<TDataReport> list = tDataReportService.selectAreaList(tDataReport);
		 return Result.OK(list);
	 }
}
